package me.ree.zkproduct.config;

import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.imps.CuratorFrameworkState;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;

@Configuration
public class CuratorConfig {

    private final String connectionStr = "127.0.0.1:2191,127.0.0.1:2192,127.0.0.1:2193";


    private CuratorFramework client;


    @Bean
    public CuratorFramework curatorFramework() {
        // 创建和配置CuratorFramework实例
        RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 3);
        client =  CuratorFrameworkFactory.newClient(connectionStr, retryPolicy);
        if (client != null && client.getState() == CuratorFrameworkState.LATENT) {
            client.start(); // 确保在非空且未启动时启动客户端
        }
        return client;
    }

    /**
     * 无法保证依赖CuratorFramework的地方，使用CuratorFramework前，CuratorFramework已经start
     */
//    @PostConstruct
//    public void startCuratorFramework() {
//        if (client != null && client.getState() == CuratorFrameworkState.LATENT) {
//            client.start();
//        }
//    }

    @PreDestroy
    public void closeCuratorFramework() {
        if (client != null && client.getState() == CuratorFrameworkState.STARTED) {
            client.close();
        }
    }
}
